import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { FormInstance } from 'antd/lib/form';
import {
  Card,
  Input,
  Row,
  Col,
  Form,
  Select,
  Button,
  Spin,
  Popconfirm,
  Space,
  Descriptions,
  Table,
  message,
  Badge,
} from 'antd';
import moment from 'moment';
import PropTypes from 'prop-types';
import { filterAuth, findDicByCodeSort } from '@/support/common';
import { transferOption } from "@/utils/common";

const enrollStatusList = [
  { dataKey: '0', dataValue: '未激活' },
  { dataKey: '1', dataValue: '激活成功' },
  { dataKey: '2', dataValue: '激活失败' },
  { dataKey: '3', dataValue: '激活进行中' },
  { dataKey: '4', dataValue: '审核中' },
  { dataKey: '5', dataValue: '审核失败' },
];
const typeAllList = [
  { dataKey: '1', dataValue: '普通用户' },
  { dataKey: '2', dataValue: '试乘试驾' },
  { dataKey: '3', dataValue: '展车' },
  { dataKey: '4', dataValue: '内部测试车' },
  { dataKey: '5', dataValue: '媒体车' },
  { dataKey: '6', dataValue: '质检车' },
];
const FormItem = Form.Item;
const mapStateToProps = (state: any) => ({
  connectQuickConfig: state.connectQuickConfig,
  saveLoading: state.loading.effects['connectQuickConfig/postObj'],
  loading: state.loading.effects['connectQuickConfig/getData'],
});
class ConnectQuickConfig extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();

  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.object,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      configList: [],
      record: {},
      history: {},
      detailLoading: false,
      selectedRowKeys: [],
      brandList: [],
      count: 0,
      sendDisabled: false
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'connectQuickConfig/getData',
      payload: { url: '/envchange/getitemlist' },
      callback: (res: any) => {
        this.setState({ configList: res.data });
      },
    });

    this.getBrand()
  }

  //  获取品牌数据
  getBrand = ()=>{
    const { dispatch } = this.props;
    dispatch({
      type: 'connectQuickConfig/getData',
      payload: {
        url: '/common/vehicle/getcurrentbrand',
      },
      callback: (res: any) => {
        if (res.statusCode === '0' && res.data !== null) {
          this.setState({ brandList: res.data });
        }
      },
    });
  }

  componentWillUnmount() {
    if (this.connectQCTimer) {
      clearInterval(this.connectQCTimer);
      this.connectQCTimer = null;
    }
  }

  getData = async (vin: any) => {
    const { dispatch } = this.props;
    this.setState({ detailLoading: true });
    let record: any = {};
    let history: any = {};
    /* await dispatch({
      type: 'connectQuickConfig/getDataWithRes',
      payload: {
        url: '/envchange/getvehicledetail',
        vin: vin,
      },
      callback: (res: any) => {
        if (res.statusCode == '0' && res.data) {
          record = res.data;
        }
      },
    }); */
    await dispatch({
      type: 'connectQuickConfig/getDataWithRes',
      payload: {
        url: '/envchange/getconfig',
        vin: vin,
      },
      callback: (res: any) => {
        if (res.statusCode == '0' && res.data) {
          history = res.data;
          const { brandId, msisdn, apnFlag} = res.data
          this.formRef.current && this.formRef.current.setFieldsValue({
            vin,
            brandId,
            msisdn,
            apnFlag
          })
        }
      },
    });
    /* if (!record || !record.vehicle || !record.vehicle.vin) {
      message.warning('车辆信息不存在，无法进行配置');
    } */
    this.setState({ record: record, history: history, detailLoading: false });
  };

  save = () => {
    const { selectedRowKeys, record } = this.state;
    const { dispatch } = this.props;
    let vin = this.formRef.current.getFieldValue('vin')
    let brandId = this.formRef.current.getFieldValue('brandId')
    let msisdn = this.formRef.current.getFieldValue('msisdn')
    let apnFlag = this.formRef.current.getFieldValue('apnFlag')
    // console.log(selectedRowKeys, record)
    // console.log(vin, brandId, msisdn, apnFlag)

    if (selectedRowKeys && selectedRowKeys.length === 0) {
      message.warning('请先选择一项配置');
      return false
    }
    if (!(vin && brandId && msisdn && apnFlag)) {
      message.warning('请先将表单填写完整');
      return false
    }

    this.setState({ 
      sendDisabled: true
    });
    message.success('配置已下发，请等待10秒后检验配置结果');
    dispatch({
      type: 'connectQuickConfig/postData',
      payload: {
        url: '/op/config/envChange/down/new', //  envchange/send
        envId: selectedRowKeys[0],
        vin,
        brandId,
        msisdn,
        apnFlag,
      },
      callback: (res: any) => {
        // message.success('配置已下发，请等待10秒后检验配置结果');
      },
    });
    let count = 10;
    this.setState({ count });
    this.connectQCTimer = setInterval(() => {
      count--;
      this.setState({ count });
      if (count === 0) {
        clearInterval(this.connectQCTimer);
        this.setState({ 
          sendDisabled: false
        });
      }
    }, 1000);
  };

  reset = () => {
    this.formRef.current?.resetFields();
    this.setState({ record: {}, history: {}, selectedRowKeys: [] });
  };

  handleSubmit = () => {
    this.formRef.current?.submit();
  };

  onFinish = (formValues: any) => {
    if (formValues && formValues.vin) {
      this.getData(formValues.vin);
    } else {
      // message.warning('请先输入所有查询条件后再查询');
      message.warning('请先输入VIN后再查询');
    }
  };

  render() {
    const { configList, brandList, record, history, detailLoading, selectedRowKeys, count, sendDisabled } = this.state;
    const {
      loading,
      saveLoading,
      location: { pathname = '/' },
    } = this.props;
    let enrollStatus = null;
    if (record && record.vehicle && record.vehicle.enrollStatus) {
      let esItem = enrollStatusList.find(
        (item: any) => item.dataKey == String(record.vehicle.enrollStatus),
      );
      if (esItem) {
        enrollStatus = esItem.dataValue;
      }
    }
    let vhlType = null;
    if (record && record.vehicle && record.vehicle.vhlType) {
      let vhlItem = typeAllList.find((item: any) => item.dataKey == String(record.vehicle.vhlType));
      if (vhlItem) {
        vhlType = vhlItem.dataValue;
      }
    }
    let changeStatus = null;
    if (history && history.changeStatus) {
      switch (String(history.changeStatus)) {
        case 'SUCCESS':
          changeStatus = <Badge status="success" text="切换成功" />;
          break;
        case 'DOING':
          changeStatus = <Badge status="processing" text="切换中" />;
          break;
        case 'FAIL':
          changeStatus = <Badge status="error" text="切换失败" />;
          break;
        case 'TIME_OUT':
          changeStatus = <Badge status="warning" text="切换超时" />;
          break;
        default:
          changeStatus = history.changeStatus;
      }
    }
    const columns = [
      {
        title: 'attConUrl',
        dataIndex: 'attConUrl',
      },
      {
        title: 'MQTT地址',
        dataIndex: 'mqttAddress',
      },
      {
        title: 'MQTT端口',
        dataIndex: 'mqttPort',
      },
      {
        title: 'MQTT用户名',
        dataIndex: 'mqttUserName',
        render: (text: any) => '****',
      },
      {
        title: 'MQTT密码',
        dataIndex: 'mqttPassWord',
        render: (text: any) => '****',
      },
      {
        title: 'attOtaUrl',
        dataIndex: 'attOtaUrl',
      },
    ];
    const mobileOperator = findDicByCodeSort(this.context.dicData,"mobileOperator");
    // let vin = this.formRef.current ? this.formRef.current.getFieldValue('vin') : ''
    
    return (
      <div>
        <Spin spinning={detailLoading}>
          <Card title="" bordered={false}>
            <Form ref={this.formRef} onFinish={this.onFinish}>
              <Row gutter={24}>
                <Col span={8}>
                  <FormItem
                    // style={{ marginBottom: 0 }}
                    label="VIN码"
                    name="vin"
                    rules={[{ pattern: /^[0-9a-zA-Z]{17}$/, message: 'VIN码只能为17位的字母和数字' }]}
                  >
                    <Input maxLength={17} style={{ minWidth: 200 }} placeholder="请输入VIN码" />
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem
                    // style={{ marginBottom: 0 }}
                    label="品牌"
                    name="brandId"
                  >
                    {/* <Input maxLength={17} style={{ minWidth: 200 }} placeholder="请输入VIN码" /> */}
                    <Select
                      allowClear
                      placeholder="请选择品牌"
                    >
                      { transferOption(brandList, ["brandCode","brandName"])}
                    </Select>
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem
                    // style={{ marginBottom: 0 }}
                    label="msisdn"
                    name="msisdn"
                  >
                    <Input maxLength={20} style={{ minWidth: 200 }} placeholder="请输入msisdn码" />
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem
                    // style={{ marginBottom: 0 }}
                    initialValue={'unicom-4G'}
                    label="移动运营商"
                    name="apnFlag"
                  >
                    <Select
                      allowClear
                      placeholder="请选择移动运营商"
                    >
                      { transferOption(mobileOperator, ["dictKey","dictValue"])}
                    </Select>
                  </FormItem>
                </Col>
                <Col span={8}>
                  
                </Col>
                <Col span={8}>
                  <span style={{ float: 'right' }}>
                    <Button size="small" type="primary" onClick={this.handleSubmit}>
                      查询
                    </Button>
                    <Button size="small" style={{ marginLeft: 8 }} onClick={this.reset}>
                      重置
                    </Button>
                  </span>
                </Col>
              </Row>
              {/* <FormItem
                style={{ marginBottom: 0 }}
                label="VIN码"
                name="vin"
                rules={[{ pattern: /^[0-9a-zA-Z]{17}$/, message: 'VIN码只能为17位的字母和数字' }]}
              >
                <Space>
                  <Input maxLength={17} style={{ minWidth: 200 }} placeholder="请输入VIN码" />
                  <Button size="small" type="primary" onClick={this.handleSubmit}>
                    查询
                  </Button>
                  <Button size="small" onClick={this.reset}>
                    重置
                  </Button>
                </Space>
              </FormItem> */}
            </Form>
          </Card>
          {/* <Card
            title="车辆信息"
            bordered={false}
            headStyle={{ fontWeight: 'bold' }}
            size="small"
            style={{ marginTop: 12 }}
          >
            <Descriptions
              bordered
              labelStyle={{ width: 120 }}
              contentStyle={{ borderRight: '1px solid #f0f0f0' }}
              size="small"
            >
              <Descriptions.Item label="VIN码">
                {record && record.vehicle && record.vehicle.vin}
              </Descriptions.Item>
              <Descriptions.Item label="品牌">{record && record.brandName}</Descriptions.Item>
              <Descriptions.Item label="车系">
                {record && record.vehicleInfo && record.vehicleInfo.seriesName}
              </Descriptions.Item>
              <Descriptions.Item label="车型">
                {record && record.vehicleInfo && record.vehicleInfo.styleName}
              </Descriptions.Item>
              <Descriptions.Item label="车型编码">
                {record && record.vehicleInfo && record.vehicleInfo.styleId}
              </Descriptions.Item>
              <Descriptions.Item label="颜色">
                {record && record.vehicleInfo && record.vehicleInfo.colorName}
              </Descriptions.Item>
              <Descriptions.Item label="车机编号">
                {record && record.bindDetail && record.bindDetail.pdsn}
              </Descriptions.Item>
              <Descriptions.Item label="TBOX编号">
                {record && record.bindDetail && record.bindDetail.tbox}
              </Descriptions.Item>
              <Descriptions.Item label="ICCID">
                {record && record.bindDetail && record.bindDetail.iccid}
              </Descriptions.Item>
              <Descriptions.Item label="激活状态">{enrollStatus}</Descriptions.Item>
              <Descriptions.Item label="激活时间">
                {record && record.vehicle && record.vehicle.enrollDate
                  ? moment(record.vehicle.enrollDate).format('YYYY-MM-DD  HH:mm:ss')
                  : null}
              </Descriptions.Item>
              <Descriptions.Item label="激活类型">{vhlType}</Descriptions.Item>
            </Descriptions>
          </Card> */}
          <Card
            title="最后下发配置"
            bordered={false}
            headStyle={{ fontWeight: 'bold' }}
            size="small"
            style={{ marginTop: 12 }}
          >
            <Descriptions bordered column={1} labelStyle={{ width: 120 }} size="small">
              <Descriptions.Item label="attConUrl">
                {history && history.attConUrl}
              </Descriptions.Item>
              <Descriptions.Item label="MQTT地址">
                {history && history.mqttAddress}
              </Descriptions.Item>
              <Descriptions.Item label="MQTT端口">{history && history.mqttPort}</Descriptions.Item>
              <Descriptions.Item label="MQTT用户名">
                {history && history.mqttUserName}
              </Descriptions.Item>
              <Descriptions.Item label="MQTT密码">
                {history && history.mqttPassWord}
              </Descriptions.Item>
              <Descriptions.Item label="attOtaUrl">
                {history && history.attOtaUrl}
              </Descriptions.Item>
              {/* <Descriptions.Item label="切换状态">{changeStatus}</Descriptions.Item> */}
              <Descriptions.Item label="下发时间">{history && history.downDt}</Descriptions.Item>
            </Descriptions>
          </Card>
          <Card
            title="可选配置（单选）"
            bordered={false}
            headStyle={{ fontWeight: 'bold' }}
            size="small"
            style={{ marginTop: 12 }}
          >
            <Table
              loading={loading}
              columns={columns}
              dataSource={configList}
              rowSelection={{
                selectedRowKeys: selectedRowKeys,
                type: 'radio',
                onChange: (selectedRowKeys: any) => {
                  this.setState({ selectedRowKeys });
                },
              }}
              rowKey={record => record.sid}
              scroll={{ x: 'max-content' }}
              size="small"
              bordered
              pagination={false}
            />
          </Card>
          {filterAuth('connectQuickConfig_doDelivery', this.context.permissions, pathname) ? (
            <div style={{ textAlign: 'center', marginTop: 12, paddingBottom: 12 }}>
              <Button
                size="small"
                type="primary"
                loading={saveLoading}
                disabled={sendDisabled}
                onClick={this.save}
              >
                配置下发
              </Button>
              {/* <Popconfirm
                title="确定配置下发？"
                placement="top"
                disabled={
                  !(
                    selectedRowKeys &&
                    selectedRowKeys.length > 0
                  )
                }
                onConfirm={this.save}
              >
                <Button
                  size="small"
                  type="primary"
                  loading={saveLoading}
                  disabled={
                    !(
                      selectedRowKeys &&
                      selectedRowKeys.length > 0
                    ) || count > 0
                  }
                >
                  配置下发{count > 0 ? '(' + count + 's)' : null}
                </Button>
              </Popconfirm> */}
            </div>
          ) : null}
        </Spin>
      </div>
    );
  }
}
export default connect(mapStateToProps)(ConnectQuickConfig);
